/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.view.saving;

import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import src.domain.saving.Savtrans;
import src.services.saving.SavtransModel;
import src.util.Messager;


/**
 *
 * @author jay
 */
@ManagedBean
@SessionScoped
public class SavtransBean implements Serializable {

    private List<Savtrans> savtranses;  
    private Savtrans selectedData, unsaveData;
    private boolean editMode = true;
    private SavtransModel helper;
    
    public SavtransBean() {
        helper = new SavtransModel();
        this.savtranses = helper.findAll(null);
        this.selectedData = null;
        this.unsaveData = null;
    }

    public boolean isEditMode() {
        return editMode;
    }
        
    public Savtrans getSelectedData() {
        return selectedData;
    }

    public Savtrans getUnsaveData() {
        return unsaveData;
    }

    public void setUnsaveData(Savtrans unsaveData) {
        this.unsaveData = unsaveData;
    }
    
    public void setSelectedData(Savtrans selectedData) {
        this.selectedData = selectedData;
    }
    
    public List<Savtrans> getSavtranses() {
        return savtranses;
    }
    
    public void handleClose(CloseEvent event) {
        this.selectedData = null;
        this.unsaveData = null;
        this.editMode = true;      
    }
    
    public void newData() {  
        this.selectedData = null;
        this.editMode = false;
        this.unsaveData = new Savtrans();
    }
    
    public void openData() { 
        this.editMode = true;
        this.unsaveData = Savtrans.clone(selectedData);
    }
    
    public void save() {
        
        RequestContext context = RequestContext.getCurrentInstance();  
        boolean success = helper.saveData(unsaveData);
        if (success==true) {
            if (this.editMode==false) this.savtranses.add(unsaveData);
            else {
                int i = savtranses.indexOf(selectedData);
                if (i <= savtranses.size()) savtranses.set(i, Savtrans.clone(unsaveData));
            }
            editMode = true;
            
        } else {
            if (this.editMode==false) unsaveData.setSavtransId(null);
        } 
        
        Messager.showSaveUpdateStatus(success);
        context.addCallbackParam("success", success);  
    }
    
    public void delete() {
        RequestContext context = RequestContext.getCurrentInstance();  
        
        boolean success = helper.deleteData(this.selectedData);
        if (success) {
            this.savtranses.remove(this.selectedData);
            this.selectedData = null;
        }
               
        Messager.showDeleteStatusConstaint(success);
        context.addCallbackParam("success", success);  
    }

}
